// App Root
var appPath = getAppPath();

// 是否延迟加载
var lazy = false;

// Datagrid ID
var datagrid_id = "#infoGrid";

// Datagrid URL参数
var datagrid_url = appPath+'/info/info_list.do';

// Dialog ID
var dialog_id = "#addInfoDlg";

// Form ID
var form_id = "#addInfoForm";

// 文本编辑器
var editor;

/**
 * jQuery加载事件
 */
$(function(){
	// 初始化Datagrid
	initPlugin();
	// 加载资讯分类
	$("#inputCategoryId").combobox({url:appPath+'/info/category_listComboAll.do',valueField:'categoryId',textField:'categoryName'});
	$("#categoryId").combobox({url:appPath+'/info/category_listCombo.do',valueField:'categoryId',textField:'categoryName'});
	
	// 初始化KE富文本编辑器
	editor = KindEditor.create('#contentHtml', {
		minWidth : '620px',
		resizeType : 1,
		allowImageUpload : true,
		uploadJson : appPath+'/info/info_uploadFile.do', // 相对于当前页面的路径
		items : [
		'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
		'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
		'insertunorderedlist', '|', 'emoticons', 'image', 'link']
	});
});

/**
 * 控件初始化方法
 */
function initPlugin() {
	$(datagrid_id).datagrid({
		url: lazy? '' : datagrid_url,
		height: "full",
		striped: true,
		remoteSort:false,
		queryParams: getQueryParam(),
		idField:'informationId',
		checkbox:true,
		frozenColumns:[[
		      {field:'ck',checkbox:true},
		      {field:'informationId',title:'操作',width:40,align:'center',
		    	  formatter:function(value,rowData,rowIndex){
		    	  	  // var dataStr = JSON.stringify(rowData);
		    		  return "<a href='javascript:void(0)'><img border='0' width='12px' height='12px'  src='"+appPath+"/js/lib/jquery-easyui/themes/icons/pencil.png' title='编辑' onClick='showEdit("+rowIndex+")'/></a>";
		    	  }
		      }
		]],
		columns:[[
		      {field:'title',title:'标题',width:390,align:'left'},
		      {field:'categoryName',title:'所属分类',width:150,align:'left'},
		      {field:'infoSource',title:'来源',width:50,align:'center',
		    	  formatter:function(value,rowData){
		    		  return iSource[value];
		    	  }
		      },
		      {field:'createTime',title:'创建时间',width:130,align:'left',
		    	  formatter:function(value,rowData){
		    		  return $.DateUtil.format(new Date(value),'yyyy-MM-dd hh:mm:ss');
		    	  }
		      },
		      {field:'updateTime',title:'更新时间',width:130,align:'left',
		    	  formatter:function(value,rowData){
		    		  return $.DateUtil.format(new Date(value),'yyyy-MM-dd hh:mm:ss');
		    	  }
		      }
		 ]],
		 pagination:true,
		 rownumbers:true,
		 onLoadSuccess: function() {
			 uncheckAll(this);
			 changeTipInfo("tommy-cell");
		 },
		 toolbar:[{
				id:'btnadd',
				text:'增加',
				iconCls:'icon-add',
				handler:function(){
					showAdd();
				}
			},'-',{
				id:'btndelMu',
				text:'删除',
				iconCls:'icon-cancel',
				handler:function(){
					var selections = $(datagrid_id).datagrid('getSelections');
					if(selections == null || selections == ''){
						$.messager.alert('提示信息','请选择要删除的数据','info');
						return ;
					}else{
						$.messager.confirm('提示信息','您确定要删除这些记录？',function(r){
							if(r){
								var ids = '';
								for(var i=0;i<selections.length;i++){
									ids += selections[i].informationId+',';
								}
								ids = ids.substring(0,ids.lastIndexOf(','));
								
								$.loading(true);
								$.ajax({
									url:appPath+'/info/info_delMulti.do',
									data:{multi_id:ids},
									success:function(data){
										$.loading(false);
										if(data!='ok'){
											$.messager.alert('提示信息','资讯有相关联的模块信息，不能删除！','info');
										}else{
											doReload('delete');
										}
									},
									error:function(XMLHttpRequest, textStatus, errorThrown){
										$.loading(false);
										$.messager.alert('提示信息','抱歉，删除未能完成，'+textStatus,'error');
									}
								});		
							}
						});
					}
				}
			}]
	});
	if (lazy)
		$(datagrid_id).datagrid('options').url = datagrid_url;
}

/**
 * 控件展现方法
 */
function showPlugin() {
	if (lazy) {
		initPlugin();
		lazy = false;
	}		
}

/**
 * 展现编辑资讯
 * @param {} rowData
 */
function showEdit(rowIndex){
	var rowData = $(datagrid_id).datagrid("getRows")[rowIndex];
	
	$(form_id).form('clear');
	$("#submitType").val("update");
	$(dialog_id).window({
		title:'编辑资讯',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});	
	$(dialog_id).window('move',{top:80});
	$(dialog_id).window('open');
	
	$.loading(true);
	$.ajax({
		url:appPath+'/info/info_single.do',
		data:{informationId:rowData["informationId"]},
		success:function(data){
			rowData = data;
			rowData.contentHtml = rowData.content;
			$(form_id).form('load',rowData);
			editor.html(rowData.contentHtml);
			$.loading(false);
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			$.loading(false);
			$.messager.alert('提示信息','抱歉，数据获取未能完成，'+textStatus,'error');
		}
	});	
}

/**
 * 提交数据（包括增加，修改）
 */
function doPostData(){
	editor.sync();
	$("#title").val($.trim($("#title").val()));
	
	if(!$(form_id).form('validate')){
		return ;
	}
	else if ($("#contentHtml").val()=='') {
		$.messager.alert('提示信息','请输入内容！','info');
		return;
	}
	
	var type = $("#submitType").val();
	var typeStr = "";
	if(type == "save"){
		typeStr = "保存";
	}else if(type == "update"){
		typeStr = "更新";
	}
	
	var subData = $(form_id);  
    var info = subData.serialize();    
	
    $.loading(true);
    if (type == "save") {
    	ajaxPostData(type, info);
    } else {
    	ajaxPostData(type, info);
    }
}

function ajaxPostData(type, info) {
	$.ajax({
		url:appPath+'/info/info_'+type + '.do',
		type:"post",
		data:info,
		success:function(data){
			$.loading(false);
			if(data == "error"){
				$.messager.alert('提示信息','该资讯已存在！','info');
			}else{
				doQuery();
				closeWindow();
			}
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			$.loading(false);
			$.messager.alert('提示信息','抱歉，'+typeStr+'未能完成，'+textStatus,'error');
		}
	});
}

/**
 * 关闭对话框
 */
function closeWindow(){
	$(dialog_id).window('close');
}

/**
 * 展现增加资讯
 */
function showAdd(){
	editor.html("");
	$(form_id).form('clear');
	$("#submitType").val("save");
	$(dialog_id).window({
		title:'增加资讯',
		iconCls:'icon-add',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$(dialog_id).window('move',{top:80});
	$(dialog_id).window('open');
}

/**
 * 获取请求信息
 * @return {}
 */
function getQueryParam(){
	var submitObject = new Object();
	var title =$.trim($('#queryTitleId').val());
	if(title&&title.length>0)submitObject.title = title;
	var categoryId = $.trim($("#inputCategoryId").combobox("getValue"));
	if(categoryId&&categoryId.length>0)submitObject.categoryId =categoryId;
	return submitObject;
}

/**
 * 查询数据
 */
function doQuery(){
	showPlugin();
	$(datagrid_id).datagrid('unselectAll');
	$(datagrid_id).datagrid('load',getQueryParam());
}

/**
 * 重载grid，取消全选
 */
function doReload(type){
	var ops = $(datagrid_id).datagrid('getPager').pagination("options");
	if(type == "save"){
		var pn = Math.floor(ops.total/ops.pageSize)+1;
		$(datagrid_id).datagrid('getPager').pagination({pageNumber:pn});
		$(datagrid_id).datagrid('options').pageNumber = pn;
	}else if(type == "delete"){
		if($(datagrid_id).datagrid('getRows').length == $(datagrid_id).datagrid('getSelections').length){
			var pn ;
			var pnt = Math.ceil(ops.total/ops.pageSize);
			var pm = ops.pageNumber;
			if(pnt == (pm-1)){
				pn = pnt ;
			}else{
				pn = pm
			}
			$(datagrid_id).datagrid('getPager').pagination({pageNumber:(pn==0?1:pn)});
			$(datagrid_id).datagrid('options').pageNumber = (pn==0?1:pn);
		}
	}
	$(datagrid_id).datagrid('unselectAll');
	$(datagrid_id).datagrid('reload');
}
